<template>
	<div class="div">
		<div class="div2">
			<h6>图片修改</h6>
			<hr>
			<div class="img">
				<el-upload class="avatar-uploader" :multipe="false" :show-file-list="true" :auto-upload="false"
					:before-upload="beforeAvatarUpload" :file-list="fileList" :on-change="handleChange"
					action="uploadAction" list-type="picture" accept="image/jpg,image/jpeg">
					<img v-if="imageUrl" :src="imageUrl" class="avatar">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
				<el-button style="background-color: #f56c6c;color: white;" @click="updatePic()">确认</el-button>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				fileList: [],
				loading: false,
				imageUrl: "",
			}
		},
		methods: {
			handleChange: function(file, fileList) {
				this.fileList = fileList;
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 512;

				if (!isJPG) {
					this.$message.error('上传图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传图片大小不能超过 0.5MB!');
				}
				return isJPG && isLt2M;
			},
			updatePic() {
				let fd = new FormData();
				let fl = this.fileList;
				if (fl.length > 0 && fl[0].raw != null) {
					fd.append("mypic", fl[0].raw);
				}
				this.$postf("/api/user/updatePic", fd).then((resp) => {
					console.log(resp.data);
				})
			}
		},
	}
</script>

<style scoped>
	.div {
		width: 100%;
	}

	.div .div2 {
		width: 100%;
		margin-top: 5vh;
		text-align: center;
	}

	.div .div2 hr {
		margin: 0 auto;
		width: 80%;
		border: 1px solid aqua;
	}
	
	.div .div2 .img {
		width: 100%;
		height: 500px;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
	}

	.div .div2 .avatar-uploader {
		border: 2px solid #d9d9d9;
		width: 300px;
		height: 300px;
		margin-bottom: 110px;
	}


	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 300px;
		height: 300px;
		line-height: 300px;
		text-align: center;
	}

	.avatar {
		width: 300px;
		height: 300px;
		display: block;
	}
</style>